import { Component, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core';
import { NzDescriptionsSize } from 'ng-zorro-antd/descriptions';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { defalutImg } from '../../../../comm';
import { secondSaleAfterModeArrs } from '../used-after-sales-manage.pipe';
import { PermissionService } from 'src/app/service/permission.service';
import { CommonService } from '../../../../services-common/common.service';
import { UsedAfterSalesManageService } from '../used-after-sales-manage.service';

@Component({
  selector: 'app-used-after-sales-detatils',
  templateUrl: './used-after-sales-detatils.component.html',
  styleUrls: ['./used-after-sales-detatils.component.scss']
})
export class UsedAfterSalesDetatilsComponent implements OnInit {
  @ViewChild('followUpRef') followUpRef: any;

  fallback = defalutImg;
  routeParams: any = {};
  descriptionSize: NzDescriptionsSize = 'middle';
  descriptionColumn = { xxl: 4, xl: 3, lg: 3, md: 3, sm: 2, xs: 1 };

  detailsData: any = {};
  // 剩余时间
  deadlineTime: number = 0;
  differDateColor: string = '';
  deadlineVisible: boolean = false;
  saleAfterTable: any = [];

  /**
   * 修改物流 Modal
   * ----------------------------------------------------------------
   */
  logisticsVisible = false;
  logisticsOptions: any = [];
  logisticsForm!: FormGroup;

  /**
   * 申请审核 Modal
   * ----------------------------------------------------------------
   */
  afterTreatmentVisible = false;
  afterTreatmentForm!: FormGroup;

  /**
   * 商品审核 Modal
   * ----------------------------------------------------------------
   */
  goodsAuditingVisible = false;
  goodsAuditingForm!: FormGroup;
  auditingImgList: any = [];
  saleAfterModeOptions: any[] = [...secondSaleAfterModeArrs]; // 售后方式

  // 跟进 Modal
  initParams: any = {
    type: 11, // type  1、订单 2、售后 3、客户 4、出库 5、直降 6、退税 7、机器 8、商品
    modelId: 2, // 类型 1、旧的表示二手回收 2、表示二手商城 3、表示二手回收
    relationInformation: ''
  };

  // 拒绝原因
  refuseReasonOptions: any[] = [];

  // 物流详情 Modal
  logisticsDetailsVisible = false;
  logisticsDetailsLoading = false;
  logisticsDetailsItem: any = {};
  logisticsDetailsArr: any = [];

  // 地址options
  addressOptions: any = [];

  constructor(
    public changeDetectorRef: ChangeDetectorRef,
    private message: NzMessageService,
    private fb: FormBuilder,
    private modal: NzModalService,
    private activatedRoute: ActivatedRoute,
    private commonService: CommonService,
    public permission: PermissionService,
    private services: UsedAfterSalesManageService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
    })
  }

  ngOnInit(): void {
    this.loadRefuseReasonOptions();
    this.loadLogisticsOptions();

    // ---------- 修改物流 Modal ----------
    this.logisticsForm = this.fb.group({
      expressType: ['', [Validators.required]], // 物流类型
      expressNum: ['', [Validators.required]] // 物流单号
    })

    // ---------- 申请审核 Modal ----------
    this.afterTreatmentForm = this.fb.group({
      updateType: [1],
      agreeType: ['', [Validators.required]], // 处理意见
      addrId: [''], // 退货地址 区ID
      refuseReason: [''], // 拒绝原因
      auditNote: [''], // 备注
      followText: [''] // 跟进备注
    })

    // ---------- 商品审核 Modal ----------
    this.goodsAuditingForm = this.fb.group({
      agreeType: ['', [Validators.required]], // 处理意见
      refundType: [''], // 售后方式
      refundPrice: [''], // 退还金额
      refuseReason: [''], // 拒绝原因
      auditNote: [''], // 拒绝备注
      imgs2: [''], // 图片附件
      isFreight: [''], // 邮费承担 0：我司 1：用户
      followText: [''] // 跟进备注
    })

    this.loadDetailsData();
  }

  // 查询地址管理options
  async getAddressListData() {
    let params = {
      page: 1,
      pageSize: 5000
    }
    const res: any = await this.services.getAddressListData(params);
    if (res.code === 0) {
      this.addressOptions = res.data?.records || [];
    } else {
      this.message.error(res.message);
    }
  }

  // 售后拒绝原因
  async loadRefuseReasonOptions() {
    this.refuseReasonOptions = await this.commonService.getDictList('es_after_sales_service_refuse_reason');
  }

  async loadDetailsData() {
    const messId = this.message.loading('数据加载中..', { nzDuration: 0 }).messageId;
    const {code, data, message}: any = await this.services.getSecondAfterSaleDetails(this.routeParams.id);
    this.message.remove(messId);

    if (code === 0) {
      this.detailsData = data || {};

      // 超时倒计时
      // this.getSurplusTime('2022-07-12 12:12:06');
      if (this.detailsData.timeoutTime) {
        this.getSurplusTime(this.detailsData.timeoutTime);
      }
      // 售后内容Table
      this.saleAfterTable = data.list || [];

      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
    } else {
      this.message.error(message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * 修改物流 Modal
   * ----------------------------------------------------------------
   */
  async loadLogisticsOptions() {
    this.logisticsOptions = await this.commonService.getDictList('logistics_company');
  }
  
  showLogisticsModal() {
    this.logisticsForm.reset();
    this.logisticsForm.patchValue({
      expressType: this.detailsData?.express?.expressCode,
      expressNum: this.detailsData?.express?.expressNum
    })
    this.logisticsVisible = true;
  }

  subLogisticsForm() {
    if (this.logisticsForm.valid) {
      this.modal.confirm({
        nzTitle: '提示',
        nzContent: '确认修改？售后状态将进入[商品已寄出]',
        nzOkText: '确认',
        nzOkType: 'primary',
        nzOkDanger: true,
        nzOnOk: async () => {
          let params = {
            refundId: this.detailsData.refundId,
            ...this.logisticsForm.value
          }
          this.logisticsVisible = true;
          const res: any = await this.services.updateSecondExpressData(params);
          this.logisticsVisible = false;
    
          if (res.code === 0) {
            this.message.success('修改物流成功');
            this.loadDetailsData();
          } else {
            this.message.error(res.message);
          }
        },
        nzCancelText: '取消'
      });
    } else {
      Object.values(this.logisticsForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * ----------------------------------------------------------------
   * 申请审核 Modal
   * ----------------------------------------------------------------
   */
  showAfterTreatmentModal() {
    this.getAddressListData();
    this.afterTreatmentVisible = true;
  }

  // Form动态验证
  afterHandleTypeChange(val: number) {
    this.afterTreatmentForm.patchValue({
      addrId: '',
      refuseReason: '',
      auditNote: ''
    })
    
    if (val === 0) {
      // 仅退款不需地址
      if (this.detailsData.type !== 4) {
        this.afterTreatmentForm.get('addrId')!.setValidators(Validators.required);
        this.afterTreatmentForm.get('addrId')!.markAsDirty();
      }

      ['refuseReason', 'auditNote', 'followText'].forEach(key => {
        this.afterTreatmentForm.get(key)!.clearValidators();
        this.afterTreatmentForm.get(key)!.markAsPristine();
      })
    } else {
      // 仅退款不需地址
      if (this.detailsData.type !== 4) {
        this.afterTreatmentForm.get('addrId')!.clearValidators();
        this.afterTreatmentForm.get('addrId')!.markAsPristine();
      }

      ['refuseReason', 'auditNote', 'followText'].forEach(key => {
        this.afterTreatmentForm.get(key)!.setValidators(Validators.required);
        this.afterTreatmentForm.get(key)!.markAsDirty();
      })
    }

    ['addrId', 'refuseReason', 'auditNote', 'followText'].forEach(key => {
      this.afterTreatmentForm.get(key)!.updateValueAndValidity();
    })
  }

  cityChange(val: any) {
    this.afterTreatmentForm.get('addrId')?.setValue(val.countyId);
  }

  async subAfterTreatmentForm() {
    if (this.afterTreatmentForm.valid) {
      let params = {
        refundId: this.detailsData.refundId,
        ...this.afterTreatmentForm.value
      }

      for (let key in params) {
        if (this.commonService.isEmpty(params[key])) {
          delete params[key]
        }
      }
      
      this.modal.confirm({
        nzTitle: '提示',
        nzContent: `${params.agreeType === 0 ? '确定同意?' : '确定拒绝吗？用户可以看到原因和备注，请注意言辞哦!'}`,
        nzOkText: '确认',
        nzOkType: 'primary',
        nzOkDanger: true,
        nzOnOk: () => {
          this.submitInterface(params);
        },
        nzCancelText: '取消'
      });
    } else {
      Object.values(this.afterTreatmentForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * ----------------------------------------------------------------
   * 售后收货
   * ----------------------------------------------------------------
   */
  showReceiving() {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确定已经收到货物?',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        let params = {
          updateType: 3,
          refundId: this.detailsData.refundId
        }
        this.submitInterface(params);
      },
      nzCancelText: '取消'
    });
  }

  /**
   * ----------------------------------------------------------------
   * 商品审核 Modal
   * ----------------------------------------------------------------
   */
  showGoodsAuditingModal() {
    this.goodsAuditingForm.reset();
    this.goodsAuditingVisible = true;
  }

  // Form动态验证
  handleOpinionsChange(val: number) {
    this.goodsAuditingForm.patchValue({
      refundType: val === 0 ? this.detailsData.type : '',
      refundPrice: '',
      refuseReason: '',
      auditNote: '',
      imgs2: '',
      isFreight: ''
    })
    this.auditingImgList = [];
    if (val === 0) {
      ['refuseReason', 'auditNote', 'isFreight', 'followText'].forEach(key => {
        this.goodsAuditingForm.get(key)!.clearValidators();
        this.goodsAuditingForm.get(key)!.markAsPristine();
      });

      ['refundType', 'refundPrice'].forEach(key => {
        this.goodsAuditingForm.get(key)!.setValidators(Validators.required);
        this.goodsAuditingForm.get(key)!.markAsDirty();
      });
    } else {
      ['refundType', 'refundPrice'].forEach(key => {
        this.goodsAuditingForm.get(key)!.clearValidators();
        this.goodsAuditingForm.get(key)!.markAsPristine();
      });

      ['refuseReason', 'auditNote', 'isFreight', 'followText'].forEach(key => {
        this.goodsAuditingForm.get(key)!.setValidators(Validators.required);
        this.goodsAuditingForm.get(key)!.markAsDirty();
      });
    }
    ['refundType', 'refundPrice', 'refuseReason', 'auditNote', 'isFreight', 'followText'].forEach(key => {
      this.goodsAuditingForm.get(key)!.updateValueAndValidity();
    });
  }

  uploadImgChange(val: any) {
    this.goodsAuditingForm.get('imgs2')?.setValue(val.length ? JSON.stringify(val) : '');
  }

  subGoodsAuditingForm() {
    if (this.goodsAuditingForm.valid) {
      let params = {
        updateType: 2,
        refundId: this.detailsData.refundId,
        ...this.goodsAuditingForm.value
      }
      
      for (let key in params) {
        if (this.commonService.isEmpty(params[key])) {
          delete params[key]
        }
      }
      
      this.modal.confirm({
        nzTitle: '提示',
        nzContent: `${params.agreeType === 0 ? '确定同意?确认后钱款将原路退回用户账户!' : '确定拒绝吗?1，用户可以看到原因和备注，请注意言辞,2，系统会自动生成出库单，请及时操作出库'}`,
        nzOkText: '确认',
        nzOkType: 'primary',
        nzOkDanger: true,
        nzOnOk: () => {
          this.submitInterface(params);
        },
        nzCancelText: '取消'
      });
    } else {
      Object.values(this.goodsAuditingForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * 提交保存(申请审核 or )
   * @param params 
   */
  async submitInterface(params: any) {
    const res: any = await this.services.updateAfterSaleHandleData(params);
    if (res.code === 0) {
      this.afterTreatmentVisible = false;
      this.goodsAuditingVisible = false;
      this.message.success('操作成功');
      this.loadDetailsData();
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * 查看物流详情
   * ----------------------------------------------------------------
   */
  showLogisticsDetailModal(item: any) {
    this.logisticsDetailsItem = {
      expressNum: item.expressNum || '',
      expressCode: item.expressCode || ''
    };
    this.loadLogisticsDetails();
    this.logisticsDetailsVisible = true;
  }

  // 查看物流详情
  async loadLogisticsDetails() {
    const {expressNum, expressCode} = this.logisticsDetailsItem || {};
    let params = {
      expressNum,
      expressCode
    }
    this.logisticsDetailsLoading = true;
    const res: any = await this.services.getLogisticsDetails(params);
    this.logisticsDetailsLoading = false;

    if (res.code === 0) {
      this.logisticsDetailsArr = !this.commonService.isEmpty(res.data?.expressTraces) ? JSON.parse(res.data?.expressTraces) : [];
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * other
   * ----------------------------------------------------------------
   */
  copyContent(str: string) {
    this.commonService.copyStr(str);
  }

  // 售后内容 | 订单售后记录 (价格 or 次数合计)
  calculatePriceTotal(arrs: any[], keys: string[]) {
    let sum = 0;
    sum = arrs.reduce((total: number, item: any) => {
      return total + (keys.length > 1 ? (item[keys[0]] - item[keys[1]]) : (item[keys[0]] || 0));
    }, 0);
    return sum;
  }

  // 售后内容 已退货 | 本次售后数 合计
  calculateNumTotal(key: string) {
    let sumArr: any[] = [];
    // if (this.saleAfterTable.length) {
    //   sum = this.saleAfterTable.reduce((total: number, item: any) => {
    //     return total + (item[key] === keyVal ? 1 : 0);
    //   }, 0)
    // }
    sumArr = this.saleAfterTable.filter((item: any) => item[key] > 0);
    return sumArr?.length || 0;
  }

  // 跟进
  followModal(val: any) {
    this.initParams.relationInformation = val;
    this.followUpRef.isModelVisible = true;
  }

  // 获取剩余时间
  getSurplusTime(date: string) {
    let nowTime = Date.now();
    let overTime = new Date(date).getTime();
    let differDate = (overTime - nowTime) / (1000 * 60 * 60);

    this.differDateColor = this.setDifferTimeColor(differDate);
    this.deadlineTime = overTime;
    this.deadlineVisible = overTime > nowTime ? true : false;
  }

  setDifferTimeColor(differNum: number) {
    if (differNum == 0) {
      return '#ff4d4f';
    } else if (differNum < 24) {
      return '#faad14';
    } else if (differNum >= 24) {
      return '#52c41a';
    } else {
      return '#d9d9d9';
    }
  }

  // img conversion
  getImgArray(str: string) {
    return !this.commonService.isEmpty(str) ? JSON.parse(str) : [];
  }

  back() {
    history.back();
  }
}
